<?php

namespace services\marketing;

use Yii;
use common\models\patient\User;
use common\components\Service;
use common\models\marketing\RiskType;
use common\models\common\TrueDeleteLog;
use common\helpers\CommonHelper;

/**
 * Class RiskTypeService
 * @package services\marketing
 */
class RiskTypeService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return RiskType|null
     */
    public function findById(int $id = 0): ?RiskType
    {
        return RiskType::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return RiskType|null
     */
    public function findInfo(array $condition = []): ?RiskType
    {
        $query = RiskType::find();

//        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
//        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
//        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = RiskType::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);
        // 判断是否获取内置
        if (isset($condition['is_builtin']) && $condition['is_builtin'] == RiskType::IS_BUILTIN_YES) {
            if (isset($condition['project_id'])) {
                $query->andWhere([
                    'or',
                    ['project_id' => $condition['project_id']],
                    ['type' => RiskType::IS_BUILTIN_YES]
                ]);
            } else {
                $query->andWhere(['type' => $condition['is_builtin']]);
            }
        } else {
            isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        }

        return $query->asArray()->all();
    }

    /**
     * 风控类型列表
     *
     * @return array
     */
    public function getList($params)
    {
        $query = RiskType::find()->select('id, risk_name, status, type')
            ->where(['status' => [RiskType::STATUS_INVALID, RiskType::STATUS_ENABLE]]);
        if (isset($params['is_builtin']) && $params['is_builtin'] == RiskType::IS_BUILTIN_YES) {
            $query->andWhere(['type' => RiskType::IS_BUILTIN_YES]);
        } else {
            $query->andWhere([
                'or',
                ['project_id' => $params['project_id']],
                ['type' => RiskType::IS_BUILTIN_YES]
            ]);
        }
        $list = $query->orderBy(['status' => SORT_DESC, 'type' => SORT_DESC, 'sort' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'list' => $list,
        ];
    }

    /**
     * 新增风控类型
     *
     * @param $params
     * @return array
     */
    public function create($params)
    {
        if (isset($params['is_builtin']) && $params['is_builtin'] == RiskType::IS_BUILTIN_YES) {
            $condition = [
                'risk_name' => $params['risk_name'],
                'type' => $params['is_builtin'],
                'status' => [RiskType::STATUS_ENABLE, RiskType::STATUS_INVALID]
            ];
        } else {
            $condition = [
                'risk_name' => $params['risk_name'],
                'project_id' => $params['project_id'],
                'status' => [RiskType::STATUS_ENABLE, RiskType::STATUS_INVALID]
            ];
        }
        $exists = $this->checkName($condition);
        if ($exists) {
            return ['code' => 422, 'message' => '该风控类型名称已存在'];
        }

        $model = new RiskType();
        $model->risk_name = $params['risk_name'];
        if (isset($params['is_builtin']) && $params['is_builtin'] == RiskType::IS_BUILTIN_YES) {
            $model->type = $params['is_builtin'];
        } else {
            $model->project_id = $params['project_id'];
        }
        $model->status = $params['status'];
        $model->operation_id = $params['member_id'];
        if ($model->save() == false) {
            return ['code' => 422, 'message' => '新增失败'];
        }
        return ['code' => 200, 'message' => '新增成功'];
    }

    /**
     * 判断是否存在
     *
     * @param $where
     * @return bool
     */
    public function checkName($where)
    {
        return RiskType::find()->where($where)->exists();
    }

    /**
     * 编辑状态
     *
     * @param int $id
     * @param int $status
     * @return array
     */
    public function updateStatus(int $id, int $status)
    {
        $exists = $this->checkName(['id' => $id]);
        if (!$exists) {
            return ['code' => 422, 'message' => '该风控类型不存在'];
        }
        $data = RiskType::updateAll(['status' => $status], ['id' => $id]);
        if (!$data) {
            return ['code' => 422, 'message' => '修改失败'];
        }
        return ['code' => 200, 'message' => '修改成功'];
    }

    /**
     * 编辑风控类型
     *
     * @param array $params
     * @return array
     */
    public function update(array $params)
    {
        $exists = $this->checkName(['id' => $params['id']]);
        if (!$exists) {
            return ['code' => 422, 'message' => '数据不存在'];
        }

        $model = RiskType::findOne($params['id']);
        if (isset($params['is_builtin']) && $params['is_builtin'] == RiskType::IS_BUILTIN_YES) {
            $condition = [
                'risk_name' => $params['risk_name'],
                'type' => $params['is_builtin'],
                'status' => [RiskType::STATUS_ENABLE, RiskType::STATUS_INVALID],
            ];
        } else {
            $condition = [
                'risk_name' => $params['risk_name'],
                'project_id' => $params['project_id'],
                'status' => [RiskType::STATUS_ENABLE, RiskType::STATUS_INVALID],
            ];
        }
        $callbackStatusIs = RiskType::findOne($condition);
        if ($callbackStatusIs && $callbackStatusIs->id != $params['id']) {
            return ['code' => 422, 'message' => '该风控类型名称已存在'];
        }

        $model->risk_name = $params['risk_name'];
        if (isset($params['is_builtin']) && $params['is_builtin'] == RiskType::IS_BUILTIN_YES) {
            $model->type = $params['is_builtin'];
        } else {
            $model->project_id = $params['project_id'];
        }
        $model->status = $params['status'];
        $model->operation_id = $params['member_id'];
        if ($model->save() == false) {
            return ['code' => 422, 'message' => '修改失败'];
        }
        return ['code' => 200, 'message' => '修改成功'];
    }

    /**
     * 删除风控类型
     *
     * @param int $id
     * @return array
     */
    public function delete(int $id)
    {
        $exists = $this->checkName(['id' => $id]);
        if (!$exists) {
            return ['code' => 422, 'message' => '该风控类型不存在'];
        }
        $data = RiskType::updateAll(['status' => RiskType::STATUS_DELETE], ['id' => $id]);
        if (!$data) {
            return ['code' => 422, 'message' => '删除失败'];
        }
        return ['code' => 200, 'message' => '删除成功'];
    }

    /**
     * @apiName 真删除,清除字段对应关系
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     * @param int $id
     * @return array
     * @throws \Exception
     */
    public function trueDelete(int $id)
    {
        // 黑名单不可删除,多处地方引用到
        if ($id == RiskType::BLACK_LIST) {
            return false;
        }

        $riskArray = RiskType::find()
            ->where(['id' => $id])
            ->asArray()
            ->one();

        if (!$riskArray) {
            return ['code' => 422, 'message' => '该效果类型不存在'];
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            $member = Yii::$app->user->identity->member;
            $data = RiskType::deleteAll(['id' => $id]);
            // 删除 用到效果类型的东西
            // 清空效果类型
            User::updateAll(['updated_at' => time(), 'risk_type_id' => 0],['risk_type_id' => $id]);
            // 记录修改记录
            $trueModel = new TrueDeleteLog();
            $trueModel->project_id = $riskArray['project_id'];
            $trueModel->delete_id = $riskArray['id'];
            $trueModel->delete_name = $riskArray['risk_name'];
            $trueModel->delete_table = RiskType::tableName();
            $trueModel->effect_table = '【' . User::tableName() . '（risk_type_id）】';
            $trueModel->operator_id = $member->id;
            $trueModel->operator_name = $member->realname;
            $trueModel->saveAndCheckResult();

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return CommonHelper::api(422, $e->getMessage());
        }

        if (!$data) {
            return ['code' => 422, 'message' => '删除失败'];
        }
    }

}
